//
//  SetTimeViewController.m
//  ALittleReminder
//
//  Created by George on 11-11-05.
//
//

#import "SetTimeViewController.h"

@implementation SetTimeViewController{
    AlertManagedObject * myAlert;
}
@synthesize datePicker;



- (id)initWithAlert:(AlertManagedObject *)alert
{
    self = [self initWithNibName:@"SetTimeViewController" bundle:nil];
    if (self) {
        myAlert = alert;
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
//When the view is shown:
//Set the selected time and minimum choosable time to now.
//If the alert already has a time. then set the selected time to the existing time.
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // get the time
    NSDate *starting = [[NSDate alloc] init];
    
    // round up seconds
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *minutes = [gregorian 
                                 components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit
                                     fromDate:starting];
    NSDateComponents *offset = [[NSDateComponents alloc] init];
    [offset setMinute:1];
    
    //have the time picker start at this time
    datePicker.date = [gregorian dateByAddingComponents:offset toDate:[gregorian dateFromComponents:minutes] options:0];
    
    //forbid from picking a time in the past
    datePicker.minimumDate = datePicker.date;
    
    //used the existing time if possible
    if (myAlert&&myAlert.date) {
        datePicker.date = myAlert.date;
    }
}

- (void)viewDidUnload
{
    myAlert = nil;
    [self setDatePicker:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)onUpdate:(id)sender {
    if (myAlert!=nil) {
        myAlert.date = datePicker.date;
    }
    return [self onExit:sender];
}

- (IBAction)onExit:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}
@end
